package com.ruoyi.factory.qylock.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.factory.archive.domain.Archive;
import com.ruoyi.factory.archive.mapper.ArchiveMapper;
import com.ruoyi.factory.qylock.domain.EsignFileVO;

import com.ruoyi.factory.qylock.service.EsignTempService;
import com.ruoyi.factory.qylock.service.QysHandleService;
import com.ruoyi.factory.qylock.utils.OkHttpUtils;
import com.ruoyi.factory.qylock.utils.UicodeBackslashU;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import okhttp3.Response;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName QysHandleImpl
 * @Description: TODO
 * @Author LiuJiaji
 * @Date 2023/6/6 0006 17:31
 **/
@Service
public class QysHandleServiceImpl implements QysHandleService {
    protected final Logger logger = LoggerFactory.getLogger(QysHandleServiceImpl.class);

    @Autowired
    private EsignTempService esignTempService;

    @Value("${erp.oracle.url}")
    private String oracleUrl;
    @Value("${erp.oracle.username}")
    private String oracleUserName;
    @Value("${erp.oracle.password}")
    private String oraclePassword;
    @Value("${qys.serenv}")
    private String serenv;

    @Autowired
    private ArchiveMapper archiveMapper;

    /**
     * @author: Liujiaji
     * @date: 2023/6/6 0006 17:35
     * @description: TODO 回调处理
     * @param: [prejson]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public AjaxResult upStatus(Map<String, String> request) {

        //根据文件id修改状态
        //解析数据
        JSONObject jsonObject = JSONObject.fromObject(request);
//        String s1 = UicodeBackslashU.unicodeToCn(jsonObject2.toString());
//        JSONObject jsonObject = JSONObject.fromObject(s1);
        String status = jsonObject.optString("status");
        int i1=0;
        //判断状态
        if("COMPLETE".equals(status)){
            String fileid = jsonObject.optString("sn");
            EsignFileVO esignFileVO = new EsignFileVO();
            esignFileVO.setFile_id(fileid);
            //先查询再修改
            //查询如果状态是已完成则跳过,如果状态为其他则修改为已完成
            String sql="";

            // 定义oracle数据库的驱动的类
            String driverClass = "oracle.jdbc.OracleDriver";
            // 定义连接的oracle的url
            String url = oracleUrl;
            // 用户名
            String username = oracleUserName;
            // 密码
            String password = oraclePassword;

            // 定义Connection连接
            Connection conn = null;
            // 定义数据库的sql执行对象
            Statement stmt = null;

            // 定义查询结果的ResultSet对象
            ResultSet rs = null;

            PreparedStatement pst = null;

            ResultSet rst = null;

            try {
                // 注册数据库的驱动程序
                Class.forName(driverClass);
                DriverManager.setLoginTimeout(60);
                // 获得数据库的连接
                conn = DriverManager.getConnection(url, username, password);
                // 创建sql执行对象
                stmt = conn.createStatement();

                sql = "SELECT * FROM ESIGN_FILE where FILE_ID = ?";
                pst = conn.prepareStatement(sql);
                pst.setObject(1,esignFileVO.getFile_id());
                rst = pst.executeQuery();
                int i = 0;
                List<EsignFileVO> reList = new ArrayList<>();
                //封装
                while (rst.next()) {
                    EsignFileVO esignfile = new EsignFileVO();
                    esignfile.setFile_id(rst.getString("FILE_ID"));
                    esignfile.setSign_flow_status(Integer.valueOf(rst.getString("SIGN_FLOW_STATUS")));
                    reList.add(esignfile);
                }

                //如果状态不是已完成则进行修改
                if(!reList.isEmpty()){
                    EsignFileVO esignFileVO1 = reList.get(0);
                    Integer sign_flow_status = esignFileVO1.getSign_flow_status();
                    if(2 != sign_flow_status){
                        sql ="UPDATE ESIGN_FILE SET FILE_STATUS = ?, SIGN_FLOW_STATUS = ?, SIGN_FLOW_DESCRIPTION = ? where FILE_ID = ?";
                        pst = conn.prepareStatement(sql);
                        pst.setObject(1,5);
                        pst.setObject(2,2);
                        pst.setObject(3,"完成");
                        pst.setObject(4,esignFileVO.getFile_id());
                        i1 = pst.executeUpdate();
                    }
                }

                if(pst != null){
                    pst.close();
                }
                if(rst != null){
                    rst.close();
                }
                if (rs != null)
                {
                    rs.close();
                }
                if (stmt != null)
                {
                    stmt.close();
                }
                if (conn != null)
                {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new AjaxResult(200,"成功",i1);
    }

    /**
     * @author: Liujiaji
     * @date: 2023/6/9 0009 13:34
     * @description: TODO 电子签章文件下载
     * @param: [response, pathstr]
     * @return: void
     **/
    @Override
    public void getEsignFileDown(HttpServletResponse response, String pathstr) throws FileNotFoundException {

        //参数校验
        String contractId = pathstr;
        // 请求契约锁需要的参数
        String url = "/contract/download";

        Map<String,String> param = new HashMap<>();
        param.put("contractId", contractId);
        param.put("downloadItems", "NORMAL");
        param.put("needCompressForOneFile", "false");
        Response responses = OkHttpUtils.okHttpGetqysxz(url, param);
        InputStream ins = null;
        if(responses.code() != 200) logger.info("电子签章下载失败");
        ins = responses.body().byteStream();

        /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
        response.setContentType("multipart/form-data");
        /* 设置文件头：最后一个参数是设置下载文件名 */
        response.setHeader("Content-Disposition", "attachment;filename=" + pathstr +".pdf");
        try {
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
            os.close();
            ins.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }
    //通过查询数据库获取模板信息及匹配流程
    public Map<String,String> getqysfileconfig2(String printTemplateID){
        Map<String,String> map = new HashMap();
        Archive archive = new Archive();
        archive.setTypeCode("dzqz");
        archive.setPcode(printTemplateID);
        List<Archive> archives = archiveMapper.selectArchiveList(archive);
        for (Archive archive1 : archives) {
            String name = archive1.getName();
            String[] split = name.split("-");
            String s = split[1];
            map.put(s,archive1.getCode());
        }
        archive.setPcode("");
        archive.setCode(printTemplateID);
        List<Archive> archives2 = archiveMapper.selectArchiveList(archive);
        Archive archive1 = archives2.get(0);
        map.put("name",archive1.getName());
        return map;
    }

    /**
     * @author: Liujiaji
     * @date: 2023/6/9 0009 13:35
     * @description: TODO 电子签章固定模板填充
     * @param: [param]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public AjaxResult eSignByTemplate(String param){
        logger.info("契约锁模板入参: "+param);
        Date date = new Date();
        long time1 = date.getTime();
        String s = date.toString();
        logger.info("请求中间服务入参时间: "+s);
        //处理请求参数
        JSONObject jsonObject = JSONObject.fromObject(param);
        String printTemplateID = jsonObject.optString("printTemplateID");
        //读取本地配置文件获取模板流程信息 根据模板id查询对应的模板
//        Map<String, String> pidmap = getqysfileconfig(printTemplateID);
        Map<String, String> pidmap = getqysfileconfig2(printTemplateID);

        //根据模板id匹配模板
        String rest = null;
        if(pidmap.get("name").contains("1001Z3BZ01")){
            //瑞丰销售合同固定模板流程01
            try {
                //瑞丰标准销售合同01  需要处理三个模板
                rest = esignTempService.handleTempPramOne(param,pidmap);
                String s2 = new Date().toString();
                logger.info("生成模板参数时间 : "+s2);
            } catch (Exception e) {
                logger.error("第一个模板报错: "+e.getMessage());
            }
        }else if(pidmap.get("name").contains("2001Z3BZ01")){
            //豪润达销售合同固定模板流程01
            try {
                //瑞丰标准销售合同01  需要处理三个模板
                rest = esignTempService.handleTempPramThree(param,pidmap);
                String s2 = new Date().toString();
                logger.info("生成模板参数时间 : "+s2);
            } catch (Exception e) {
                logger.error("第一个模板报错: "+e.getMessage());
            }
        } else if(pidmap.get("name").contains("1001Z3BZ02")){
            rest = esignTempService.handleTempPramTwo(param);
        }else{
            JSONObject res = new JSONObject();
            res.put("code",1);
            return new AjaxResult(200,"请求成功",res);
        }
        //封装数据
        String url = "/contract/createbycategory";
        //请求契约锁
        logger.info("请求契约锁发起电子签约url: " + url);
        logger.info("请求契约锁参数 : "+rest);
        String s2 = new Date().toString();
        String res2 = OkHttpUtils.okHttpPostqys(url, rest);
        String s3 = new Date().toString();
        res2 = UicodeBackslashU.unicodeToCn(res2);
        logger.info("请求契约锁发起电子签约返参: " + res2);
        //处理返回结果
        JSONObject res = JSONObject.fromObject(res2);
        Date date2 = new Date();
        long time2 = date2.getTime();
        String s4 = date2.toString();
        logger.info("请求中间服务结束时间 : "+s4);
        Long ztime = time2-time1;
        BigDecimal divide = new BigDecimal(ztime).divide(new BigDecimal("1000"), 2);
        logger.info("请求中间服务总时间 : "+divide.toString());
        return new AjaxResult(200,"请求成功",res);
    }

    public Map<String,String> getqysfileconfig(String printTemplateID){
        Map<String,String> pidmap = new HashMap<>();
        try {
            String encoding = "UTF-8"; // 字符编码(可解决中文乱码问题 )
            File file = new File("D:\\home\\ruifeng\\propfile\\dzqzconfig.txt");//此处写的绝对路径，根据自己的文件更改路径
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTXT = null;
                int i = 1;
                while ((lineTXT = bufferedReader.readLine()) != null) {
                    System.out.println("***********读取第"+i+"行");
                    i++;
                    String trim = lineTXT.toString();
                    System.out.println(trim);
                    boolean contains = trim.contains("=");
                    if (contains) {
                        String substring = trim.substring(0, 2);
                        boolean env = substring.contains(serenv);
                        if(env){
                            if(trim.contains(printTemplateID)){


                            String[] split = trim.split("=");
                            String trim2 = split[1].trim();
                            String trim3 = split[2].trim();
                            String trim4 = split[3].trim();
                            String[] split1 = trim4.split("-");
                            if(split1.length>=4){
                                String s = split1[0];
                                String s1 = split1[1];
                                String s2 = split1[2];
                                String s3 = split1[3];
                                pidmap.put("s",s);
                                pidmap.put("s1",s1);
                                pidmap.put("s2",s2);
                                pidmap.put("s3",s3);
                            }
                            pidmap.put(trim2,trim3);
                            }
                        }
                    }
                }
                read.close();
            } else {
                logger.info("找不到指定的文件！");
                System.out.println("找不到指定的文件！");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return pidmap;
    }

    /**
     * @author: Liujiaji
     * @date: 2023/6/26 0026 15:33
     * @description: TODO 获取固定模板签章流程
     * @param: [param]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public AjaxResult normalTemplateInfo(String param){
        //处理参数
        JSONObject paramj = JSONObject.fromObject(param);
        String billtype = paramj.optString("billtype");
        if(!billtype.contains("ZY")){
            billtype = paramj.optString("billtype")+"BZ";
        }else if("Z2ZY".equals(billtype)){
            //自由模板统一使用 销售合同的签章流程
            billtype = "Z3ZY";
        }
        // 数据库配置模式
        String pk_org = paramj.optString("pk_org");
        Archive archive = new Archive();
        archive.setTypeCode("dzqz");
        archive.setPcode(pk_org);
        archive.setName(billtype);
        List<Archive> archives = archiveMapper.selectArchiveList(archive);
        JSONArray jsonArray = new JSONArray();

        if(!archives.isEmpty()){
            for (Archive archive1 : archives) {
                String code = archive1.getCode();
                String name = archive1.getName();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",code);
                jsonObject.put("name",name);
                jsonArray.add(jsonObject);
            }
            return new AjaxResult(200,"请求成功",jsonArray);
        }

        return new AjaxResult(200,"请求成功",jsonArray);
//        Map<String,String> pramm = new HashMap<>();
//        pramm.put("companyId",paramj.optString("pk_org"));
//        Map<String, String> config = Configbyqys.getConfig(pramm);
//        String companyname = config.get("companyname");
//        String companycode = config.get("companycode");
//        String url = "/v2/category/group";
//        JSONObject json = new JSONObject();
//        JSONObject json2 = new JSONObject();
//        json2.put("name",companyname);
//        json.put("company",json2);
//        String params = json.toString();
//        //请求契约锁
//        String res = OkHttpUtils.okHttpPostqys(url, params);
//        //处理返回结果
//        res = UicodeBackslashU.unicodeToCn(res);
//        //处理返回结果
//        JSONObject resj = JSONObject.fromObject(res);
//        JSONObject result = resj.getJSONObject("result");
//        JSONArray children = result.getJSONArray("children");
//        JSONArray findliuc = findliuc(children, companycode);
//        JSONArray findliuc2 = findliuc(findliuc, billtype);
//        return new AjaxResult(200,"请求成功",findliuc2);

    }

    public static JSONArray findliuc (JSONArray jsa, String type){
        for (Object child : jsa) {
            JSONObject jsonObjects = (JSONObject)child;
            String name = jsonObjects.getString("name");
            if(name.contains(type)){
                JSONArray jsonArray = jsonObjects.optJSONArray("categoryList");
                if(null != jsonArray && !jsonArray.isEmpty()) return jsonArray;
                return jsonObjects.optJSONArray("children");
            }else {
                JSONArray children = null;
                try {
                    children = jsonObjects.optJSONArray("children");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (children != null && !children.isEmpty()) {
                    JSONArray res = findliuc(children, type);
                    if(null != res && !res.isEmpty()){
                        return findliuc(children, type);
                    }
                }
            }
        }
        return null;
    }

    @Override
    public AjaxResult signByFileqys(String param){
        JSONObject paramj = JSONObject.fromObject(param);
        String companyname = archiveMapper.selectCompanyByPkid(paramj.optString("pk_org"));
        paramj.remove("pk_org");
        paramj.put("tenantName",companyname);
        JSONArray jsonObject = paramj.optJSONArray("signatories");
        for (Object o : jsonObject) {
            JSONObject jsonObject1 = (JSONObject)o;
            jsonObject1.put("tenantName",companyname);
            JSONArray jsonArray = jsonObject1.optJSONArray("actions");
            for (Object o1 : jsonArray) {
                JSONObject jsonObject2 = (JSONObject)o1;
                jsonObject2.put("name",companyname);
            }
        }
        String params = paramj.toString();
        String url = "/contract/createbycategory";
        String res2 = OkHttpUtils.okHttpPostqys(url, params);
        res2 = UicodeBackslashU.unicodeToCn(res2);
        //处理返回结果
        JSONObject res = JSONObject.fromObject(res2);
        return new AjaxResult(200,"请求成功",res);
    }

    @Override
    public AjaxResult querySignPageUrl(String param){
        JSONObject paramj = JSONObject.fromObject(param);
        String signFlowId = paramj.optString("signFlowId");
        String userphone = paramj.optString("userphone");
        String companyname = archiveMapper.selectCompanyByPkid(paramj.optString("pk_org"));
        Map<String, String> prams = new HashMap<>();
        prams.put("tenantName",companyname);
        prams.put("tenantType","COMPANY");
        prams.put("contractId",signFlowId);
        prams.put("contact",userphone);
        String params = JSONObject.fromObject(prams).toString();
        String url = "/contract/signurl/v3";
        String res2 = OkHttpUtils.okHttpPostqys(url, params);
        res2 = UicodeBackslashU.unicodeToCn(res2);
        //处理返回结果
        JSONObject res = JSONObject.fromObject(res2);
        return new AjaxResult(200,"请求成功",res);
    }



}
